package com.albon.soccer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.albon.sportsalarm.R;
import com.albon.util.Logg;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;



public class SoccerJsonPaser implements Serializable 
{
	private final String TAG = "SoccerParser";
	private String soccer_host;
	private String soccer_link;
	private Context context;
	private Handler handler;
	private Source source;
	
	private String year;
	private String month;
	private String league;
	private ProgressDialog pDialog = null;
	
	private ArrayList<HashMap<String, String>> data;
	private int world = 0;
	private String mYear;
	private String mMonth;
	private  String[] notification_time_array_name =  {};
	public SoccerJsonPaser(Context context, Handler handler, ArrayList<HashMap<String, String>> data, int world, String mYear, String mMonth, String league)
	{
		this.context = context;
		this.handler = handler;
		this.data = data;
		this.world = world;
		this.mYear = mYear;		
		this.mMonth = mMonth;
		this.league = league;
		notification_time_array_name = context.getResources().getStringArray(R.array.notification_time_array_name);
	}
	
	public void parser() {
		year = mYear;
		month = mMonth;
		league = league;
		
		String sports = "soccer";
		
    	String league = "";
    	String sort = "";
    	String date = "0";
    	
    	soccer_host = "http://211.110.184.29:3000/schedule";
    	soccer_link = "/" + sports +
    				  "/" + sort +
    				  "/" + date +
    				  "/" + league;
    	
		try {
			process();
		} catch(IOException e){
			e.printStackTrace();
		}
	}
	
    public String getStringFromUrl(String url) throws UnsupportedEncodingException {
		// 입력스트림을 "UTF-8" 를 사용해서 읽은 후, 라인 단위로 데이터를 읽을 수 있는 BufferedReader 를 생성한다.
		BufferedReader br = new BufferedReader(new InputStreamReader(getInputStreamFromUrl(url), "UTF-8"));
		
		// 읽은 데이터를 저장한 StringBuffer 를 생성한다.
		StringBuffer sb = new StringBuffer();
		
		try {
			// 라인 단위로 읽은 데이터를 임시 저장한 문자열 변수 line
			String line = null;
			
			// 라인 단위로 데이터를 읽어서 StringBuffer 에 저장한다.
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	} // getStringFromUrl

	
	/**
	 *  getInputStreamFromUrl : 주어진 URL 에 대한 입력 스트림(InputStream)을 얻는다.
	 */
	public static InputStream getInputStreamFromUrl(String url) {
		InputStream contentStream = null;
		try {
			// HttpClient 를 사용해서 주어진 URL에 대한 입력 스트림을 얻는다.
			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = httpclient.execute(new HttpGet(url));
			contentStream = response.getEntity().getContent();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return contentStream;
	} // getInputStreamFromUrl
	
	public void progressStatus(int total) {
		pDialog.setProgress(total);
	}
	
	private void process() throws IOException {

		new Thread() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
//				URL nURL;
				try {
//					nURL = new URL(soccer_host + soccer_link);
					String nURL = soccer_host + soccer_link;
					
					handler.post(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							pDialog = ProgressDialog.show(context, "", "로딩중");
							pDialog.setCancelable(true);
						}
					});
					
					data.clear();
					
					/***********************
					 * Json Data
					 * ********************/
					try {
						String line = getStringFromUrl(nURL);
						
						/* 넘어오는 데이터 구조 { [ { } ] } JSON 객체 안에 배열안에 내부JSON 객체*/
						
						/* URL 요청시 넘어오는 JSON 데이터 값
						{
						    "result_code": 200,
						    "total_count": 183,
						    "kkt_list": [	// ㅜㅜ
						        {
						            "continentname": "아시아",
						            "nationname": "한국",
						            "instituteid": "3431",
						            "institutename": "(유)대영티엠아이",
						            "institutetype": "01",
						            "continentcode": "EA0001",
						            "nationcode": "KOR",
						            "address": "[565-901] 전북 완주군 봉동읍 구미리 837-3번지",
						            "phone": "063-214-9011",
						            "fax": "063-214-0236",
						            "description": "회사구분: 교정기관\r주요제품: 만능재료시험기\r현황: 교정실..현장",
						            "linkageinstituteid": "KOLAS",
						            "linkagepage": "http://www.kolas.go.kr/WebApp/Main/Search/Search0010.aspx?CompanyNo=3431&AccreditNo=3899"
						        },
						        {
						            "continentname": "아시아",
						            "nationname": "한국",
						            "instituteid": "3231",
						            "institutename": "한국건설생활환경시험연구원(시험)",
						            "institutetype": "01",
						            "continentcode": "EA0001",
						            "nationcode": "KOR",
						            "address": "[153-803] 서울 금천구 가산동 459-28",
						            "phone": "02-2102-2500",
						            "fax": "02-838-7891",
						            "description": "회사구분: 법인\r주요제품: 안전인증 및 자율안전, 계측교정, 시험분석, 품질보증, 인증심사업무\r\n\r현황: 만능재료시험기 등 408종 908점",
						            "linkageinstituteid": "KOLAS",
						            "linkagepage": "http://www.kolas.go.kr/WebApp/Main/Search/Search0010.aspx?CompanyNo=3231&AccreditNo=3051"
						        },
						       ... 생략
						    ]
						    [
								  {
								    "date": "5월 12일 (일)",
								    "time": "17:00",
								    "a_team": "SK",
								    "b_team": "넥센",
								    "score": "5:8",
								    "place": "목동"
								  },
								  {
								    "date": "5월 12일 (일)",
								    "time": "17:00",
								    "a_team": "NC",
								    "b_team": "두산",
								    "score": "17:5",
								    "place": "잠실"
								  },
								  {
								    "date": "5월 12일 (일)",
								    "time": "17:00",
								    "a_team": "LG",
								    "b_team": "롯데",
								    "score": "3:8",
								    "place": "사직"
								  },
								  {
								    "date": "5월 12일 (일)",
								    "time": "17:00",
								    "a_team": "KIA",
								    "b_team": "삼성",
								    "score": "4:5",
								    "place": "포항"
								  }
								]
						}
						*/
						
						// 원격에서 읽어온 데이터로 JSON 객체 생성
						JSONObject object = new JSONObject(line);
						HashMap<String, String> hashmap = null;
						
						// "kkt_list" 배열로 구성 되어있으므로 JSON 배열생성
						//JSONArray Array = new JSONArray(object.getString("kkt_list"));
						JSONArray Array = new JSONArray(line);
						
						Logg.d(TAG, line);
					
						for (int i = 0; i < Array.length(); i++) {
							
							hashmap = new HashMap<String, String>();
							// bodylist 배열안에 내부 JSON 이므로 JSON 내부 객체 생성
							JSONObject insideObject = Array.getJSONObject(i);

							// StringBuffer 메소드 ( append : StringBuffer 인스턴스에 뒤에 덧붙인다. )
							// JSONObject 메소드 ( get.String(), getInt(), getBoolean() .. 등 : 객체로부터 데이터의 타입에 따라 원하는 데이터를 읽는다. )
							
							hashmap.put("real_date",	insideObject.getString("date"));
							hashmap.put("real_time",	insideObject.getString("time"));
							hashmap.put("stadium",	    insideObject.getString("place"));
							hashmap.put("a_team",		insideObject.getString("a_team"));
							hashmap.put("b_team",		insideObject.getString("b_team"));
							hashmap.put("score",		insideObject.getString("score"));
							
							
							
						} // for
						
						data.add(hashmap);
						
					} catch (JSONException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}

					handler.post(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							//Logg.d(TAG, "==끝==");
							pDialog.dismiss();
							
							handler.sendEmptyMessage(0);
						}
					});
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
			
		}.start();
	}
	
	private Soccer call_alarm_values(String key_compare_date, String key_a_team, String key_b_team){
    	Soccer soccer = null;
    	SQLiteDatabase databse = null;		
		if(databse == null){
			databse = context.openOrCreateDatabase(DatabaseHelper.DATABASE_NAME, SQLiteDatabase.CREATE_IF_NECESSARY, null);
		}
		String stringWhere = " WHERE " + DatabaseHelper.DATABASE_COLUMN_COMPARE_DATE + " = '" +key_compare_date+"' and "+ DatabaseHelper.DATABASE_COLUMN_A_TEAM +" = '"+key_a_team+"' and "+DatabaseHelper.DATABASE_COLUMN_B_TEAM+" = "+"'"+key_b_team+"'";		
		
		Cursor cursor = null;

		try {
			cursor = databse.rawQuery("SELECT "
					+ DatabaseHelper.DATABASE_COLUMN_ID + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ENABLED + ", "
					+ DatabaseHelper.DATABASE_COLUMN_REAL_DATE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_REAL_TIME + ", "
					+ DatabaseHelper.DATABASE_COLUMN_COMPARE_DATE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SETTING_YEAR + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SETTING_MONTH + ", "
					+ DatabaseHelper.DATABASE_COLUMN_REAGUE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_STADIUM + ", "
					+ DatabaseHelper.DATABASE_COLUMN_A_TEAM + ", "
					+ DatabaseHelper.DATABASE_COLUMN_B_TEAM + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SCORE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_TITLE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_RINGTONE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_VOLUME + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_VIBRATE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_AUTO_OFF_TIME + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SMS + ", "
					+ DatabaseHelper.DATABASE_COLUMN_VIDEO + ", "
					+ DatabaseHelper.DATABASE_COLUMN_RECORD + ", "						
					+ DatabaseHelper.DATABASE_COLUMN_HIGHLIGHT + ", "						
					+ DatabaseHelper.DATABASE_COLUMN_POWER + ", "													
					+ DatabaseHelper.DATABASE_COLUMN_NOTIFICATION + ", "													
					+ DatabaseHelper.DATABASE_COLUMN_EXPLANATION + " " + " FROM "
					+ DatabaseHelper.DATABASE_TABLE_NAME + " " + stringWhere, null);
			if (cursor != null && cursor.moveToFirst()) {
				do {
					
					soccer = new Soccer(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10), cursor.getString(11), cursor.getString(12), cursor.getString(13), cursor.getString(14), cursor.getString(15), cursor.getString(16), cursor.getString(17), cursor.getString(18), cursor.getString(19), cursor.getString(20), cursor.getString(21), cursor.getString(22), cursor.getString(23));
					
				} while (cursor.moveToNext());
			}		
					
								
		} finally {
			if (cursor != null)
				cursor.close();
			if(databse != null){
				databse.close();
			}
		}
		return soccer;
    }
}
